<template>
  <div class="login-container">
    <!-- 主内容容器：包含登录表单和背景装饰 -->
    <div class="p-5 pt-12 h-[calc(100vh-40px)] flex flex-col items-center relative" style="z-index: 1">
      <!-- 返回按钮：点击返回上一页 -->
      <div class="absolute top-5 left-5">
        <button @click="$router.back()" class="text-white text-xl hover:text-white/80 transition-colors">
          <i class="fas fa-arrow-left"></i>
        </button>
      </div>

      <!-- 登录表单区域：包含手机号/验证码输入和登录按钮 -->
      <div class="zindex-top w-full pt-[110px] max-w-sm">
        <div class="text-center mb-10">
          <h1 class="text-3xl font-bold text-white mb-2 drop-shadow-lg">快猫短剧</h1>
          <p class="text-white/80 text-base">更快一步，猫到更多短剧</p>
        </div>

        <div class="w-full max-w-sm">
          <!-- 手机号输入模块：验证11位有效手机号 -->
          <div class="mb-6">
            <label class="block text-white/90 text-sm font-medium mb-2">手机号</label>
            <div class="relative">
              <input
                v-model="phoneNumber"
                type="tel"
                placeholder="请输入手机号"
                class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/60 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-white/30 focus:border-white/30"
                maxlength="11"
                @input="validatePhone"
              />
            </div>
            <p v-if="phoneError" class="text-red-300 text-sm mt-1">
              {{ phoneError }}
            </p>
          </div>

          <!-- 验证码输入模块：验证6位数字验证码 -->
          <div class="mb-6">
            <label class="block text-white/90 text-sm font-medium mb-2">验证码</label>
            <div class="relative flex gap-3">
              <input
                v-model="verificationCode"
                type="text"
                placeholder="请输入验证码"
                class="flex-1 px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/60 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-white/30 focus:border-white/30"
                maxlength="6"
                @input="validateCode"
              />
              <button
                @click="sendVerificationCode"
                :disabled="!canSendCode || countdown > 0"
                class="px-4 py-3 bg-white/20 hover:bg-white/30 disabled:bg-white/10 text-white text-sm rounded-lg transition-colors font-medium backdrop-blur-sm border border-white/20 disabled:cursor-not-allowed min-w-[100px]"
                :class="{ disabled: !canSendCode || countdown > 0 }"
              >
                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
              </button>
            </div>
            <p v-if="codeError" class="text-red-300 text-sm mt-1">
              {{ codeError }}
            </p>
          </div>

          <!-- 登录提交按钮：验证通过后触发登录逻辑 -->
          <button
            @click="handleLogin"
            :disabled="!canLogin"
            class="w-full py-4 bg-white/90 text-purple-600 font-semibold rounded-lg hover:bg-white disabled:bg-white/50 disabled:text-purple-400 transition-all duration-200 shadow-lg hover:shadow-xl disabled:cursor-not-allowed"
            :class="{ disabled: !canLogin }"
          >
            {{ isLoggingIn ? '登录中...' : '登录' }}
          </button>

          <!-- 用户协议勾选：必须同意才能登录 -->
          <div class="mt-5">
            <label class="flex items-start gap-3 cursor-pointer">
              <input v-model="agreedToTerms" type="checkbox" class="mt-1 w-4 h-4 accent-white/80" />
              <span class="text-white/80 text-sm leading-relaxed flex-1">
                我已阅读并同意
                <a href="#" class="text-white hover:text-white/90 underline" @click.stop>《用户协议》</a>和
                <a href="#" class="text-white hover:text-white/90 underline" @click.stop>《隐私政策》</a>
              </span>
            </label>
          </div>
        </div>
      </div>

      <!-- 底部装饰 -->
      <div class="decoration">
        <div class="decoration-circle circle-1"></div>
        <div class="decoration-circle circle-2"></div>
        <div class="decoration-circle circle-3"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
// Vue核心API
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

// 用户相关API
import { reqSendCode, reqLoginByCode, reqGetUserInfo } from '@/apis/user'

// 引入全局状态管理以存储用户信息
import { useUserStore } from '@/stores/user'
// 实例化用户状态存储
const userStore = useUserStore()

// 响应式数据定义
const router = useRouter() // 路由实例
const phoneNumber = ref('18222222222') // 手机号输入值
const verificationCode = ref('') // 验证码输入值
const phoneError = ref('') // 手机号错误提示
const codeError = ref('') // 验证码错误提示
const countdown = ref(0) // 验证码倒计时（秒）
const isLoggingIn = ref(false) // 登录请求状态
const agreedToTerms = ref(true) // 用户协议勾选状态

// 计算属性：是否允许发送验证码（手机号11位且无错误）
const canSendCode = computed(() => {
  return phoneNumber.value.length === 11 && !phoneError.value
})

// 计算属性：是否允许登录（所有输入验证通过且勾选协议）
const canLogin = computed(() => {
  return (
    phoneNumber.value.length === 11 &&
    verificationCode.value.length === 6 &&
    !phoneError.value &&
    !codeError.value &&
    agreedToTerms.value
  )
})

// ⏯️手机号验证方法：使用正则校验11位有效手机号
const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/ // 手机号正则（1开头+3-9号段+9位数字）
  if (!phoneNumber.value) {
    phoneError.value = '' // 清空错误提示
  } else if (!phoneRegex.test(phoneNumber.value)) {
    phoneError.value = '请输入正确的手机号' // 正则匹配失败提示
  } else {
    phoneError.value = '' // 验证通过清空提示
  }
}

// ⏯️验证码验证方法：校验6位数字格式
const validateCode = () => {
  if (!verificationCode.value) {
    codeError.value = '' // 清空错误提示
  } else if (!/^\d{6}$/.test(verificationCode.value)) {
    codeError.value = '验证码为6位数字' // 格式错误提示
  } else {
    codeError.value = '' // 验证通过清空提示
  }
}

// ⭐ 发送验证码方法：触发倒计时并模拟发送逻辑
const sendVerificationCode = async () => {
  if (!canSendCode.value || countdown.value > 0) return // 未满足条件时不执行

  countdown.value = 60 // 初始化60秒倒计时
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer) // 倒计时结束清除定时器
    }
  }, 1000)

  try {
    // 发送验证码
    const { data } = await reqSendCode(phoneNumber.value)

    verificationCode.value = data.code // 开发环境下自动填充验证码，方便测试

    alert(`验证码已发送到 ${phoneNumber.value}`)
  } catch (error) {
    console.error('发送验证码失败:', error)
    alert('发送验证码失败，请重试')
    countdown.value = 0 // 发送失败重置倒计时
  }
}

// ⭐ 登录处理方法：验证通过后提交登录请求
const handleLogin = async () => {
  if (!canLogin.value) return // 未满足登录条件时不执行

  isLoggingIn.value = true // 标记登录中状态

  try {
    // 调用 登录API
    const loginResponse = await reqLoginByCode({
      phone: phoneNumber.value,
      code: verificationCode.value
    })

    // 用一个全局状态管理工具来存储 token
    await userStore.setToken(loginResponse.data.token)

    // 登录成功后获取用户信息
    await handleUserInfo()
  } catch (error) {
    console.error('登录失败:', error)
    alert('登录失败，请重试')
  } finally {
    isLoggingIn.value = false
  }
}

// ⭐ 获取用户信息并存储
const handleUserInfo = async () => {
  try {
    // 登录成功后获取用户信息
    const userInfoResponse = await reqGetUserInfo()

    console.log('用户信息:', userInfoResponse.data)

    // 用一个全局状态管理工具来存储用户信息
    userStore.setUserInfo(userInfoResponse.data)
    router.push('/my') // 跳转到用户主页
  } catch (error) {
    console.error('获取用户信息失败:', error)
    alert('获取用户信息失败，请重试')
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

/* 底部装饰动画 */
.decoration {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 200px;
  overflow: hidden;
  z-index: 0; /* 修改为0，确保装饰在最底层 */
}

.decoration-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 100px;
  height: 100px;
  bottom: 20px;
  left: 20px;
  animation-delay: 0s;
}

.circle-2 {
  width: 80px;
  height: 80px;
  bottom: 60px;
  left: 120px;
  animation-delay: 2s;
}

.circle-3 {
  width: 60px;
  height: 60px;
  bottom: 30px;
  right: 40px;
  animation-delay: 4s;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .form-section {
    max-width: 280px;
  }

  .code-wrapper {
    flex-direction: column;
    gap: 8px;
  }

  .send-code-btn {
    align-self: flex-start;
  }
}

.zindex-top {
  z-index: 99;
}
</style>
